package com.qububu.db.dao.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

import com.qububu.db.dao.TalkDao;
import com.qububu.play.common.dto.ActionTalkoverDto;
import com.qububu.play.common.dto.ActionTalkoverDto.Type;
import com.qububu.utils.ParamConverter;
import com.qububu.utils.SystemUtil;

public class TalkDaoImpl implements TalkDao {

	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public boolean saveTalkMessages(List<ActionTalkoverDto> talkOverList) {
//		System.out.println("\n\n\n------批量存入聊天的数据信息---->size->" + talkOverList.size()+"----\n\n");
		String sql = "insert into action_talkover(content, time, author_id, author_name, action_id, action_type) values(?, ?, ?, ?, ?, ?)";
		final List<ActionTalkoverDto> insertList = talkOverList;
		jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			
			public void setValues(PreparedStatement ps, int no) throws SQLException {
				ActionTalkoverDto talk = insertList.get(no);
				int i = 0;
				ps.setString(++i, talk.getContent());
				ps.setInt(++i, talk.getTime());
				ps.setInt(++i, ParamConverter.convertToInteger(SystemUtil.decrypt(talk.getAuthorId())));
				ps.setString(++i, talk.getAuthorName());
				ps.setInt(++i, ParamConverter.convertToInteger(SystemUtil.decrypt(talk.getActionId())));
				ps.setInt(++i, talk.getType().toIntValue());
			}
			
			public int getBatchSize() {
				return insertList.size();
			}
		});
		
		return true;
	}

	public List<ActionTalkoverDto> getTalkMessages(int actionType,
			String actionId) {
		int reActionId = ParamConverter.convertToInteger(SystemUtil.decrypt(actionId));
		String sql = "select * from action_talkover where action_type=? and action_id=? ORDER BY time DESC";
		
		List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql, new Object[]{actionType, reActionId});
		List<ActionTalkoverDto> talkList = new ArrayList<ActionTalkoverDto>();
		ActionTalkoverDto talk = null;
		for (Map<String, Object> elem: resultList) {
			talk = new ActionTalkoverDto();
			talk.setActionId(actionId);
			talk.setAuthorId(SystemUtil.encrypt(String.valueOf(elem.get("author_id"))));
			talk.setAuthorName(String.valueOf(elem.get("author_name")));
			talk.setTime(Integer.parseInt(String.valueOf(elem.get("time"))));
			talk.setContent(String.valueOf(elem.get("content")));
			talk.setTalkId(SystemUtil.encrypt(String.valueOf(elem.get("talk_id"))));
			talk.setType(Type.getType(Integer.parseInt(String.valueOf(elem.get("action_type")))));
			
			talkList.add(talk);
		}
		
		return talkList;
	}

}
